package work.xiaohong.arithmetic.IO;

import lombok.Cleanup;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/10/27 0027 13:06
 * @description 字符缓冲流
 * 高效读写 支持输入换行符 可写一行、读一行
 */
public class BuffereReaderAndBuffereWriter {

    public static void main(String[] args) throws Exception {
//        writeFile();
        readFile();
    }

    // 写入字符
    public static void writeFile() throws Exception {

        FileWriter fileWriter = new FileWriter("a.txt");
        @Cleanup
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write("好好学习");
        bufferedWriter.flush();

    }


    // 读取字符
    public static void readFile() throws Exception {
        FileReader fileReader = new FileReader("a.txt");
        @Cleanup
        BufferedReader bufferedReader = new BufferedReader(fileReader);

//        char[] buffer = new char[2];
//        int data = 0;
//        // fileReader.read返回的是读取到的字符个数，到尾部了就返回-1
//        while ((data = bufferedReader.read(buffer)) != -1){
//            System.out.println(new String(buffer,0,data));
//        }

        String line = null;
        while ((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }

    }




}
